package com.java;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

class Obj{
    public void doSay(){
        System.out.println("Hello Reference");
    }
    @Override
    protected void finalize() throws Throwable {
        System.out.println(Thread.currentThread().getName()+"===finalize()==");
    }
}
//-Xmx6m -Xms6m -XX:+PrintGC
public class ReferenceTests {

    static void strongReference(){
        Map<String,Object> cache=new HashMap<>();
        cache.put("k1", new Obj());
        cache.put("k2", new Obj());
    }

    static void softReference(){
        Map<String, SoftReference<Obj>> cache=new HashMap<>();
        cache.put("k1", new SoftReference<>(new Obj()));
        cache.put("k2", new SoftReference<>(new Obj()));
    }

    static ReferenceQueue<Object> referenceQueue=new ReferenceQueue();
    static Map<String, WeakReference<Obj>> cache=new HashMap<>();
    static void weakReference(){
        cache.put("k1", new WeakReference<>(new Obj(),referenceQueue));
        cache.put("k2", new WeakReference<>(new Obj(),referenceQueue));
        if(cache.get("k1").get()!=null){
            cache.get("k1").get().doSay();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //strongReference();
        //softReference();
        weakReference();
        byte[] array1=new byte[1024*1024];
        byte[] array2=new byte[1024*1024];
        byte[] array3=new byte[1024*1024];

        //byte[] array4=new byte[1024*1024];
        System.gc();
        while(true) {
            System.out.println(referenceQueue.poll());
            TimeUnit.SECONDS.sleep(1);
        }

    }
}
